const http  = require("http");
const url = require("url");
const fs = require("fs");
const server = http.createServer((req,res)=>{
    
    res.setHeader("content-type","text/html;charset=utf-8");
    let obj = url.parse(req.url,true);
    // console.log(obj);
    let {pathname,query} = obj;  // 去掉参数之后的 地址
    if(pathname==="/register"){
        console.log(query);
        if(!fs.existsSync("./data.js")){
            fs.writeFileSync("./data.js",JSON.stringify([query]));
        }else{
           let data = JSON.parse( fs.readFileSync("./data.js"));
           data.push(query);
           fs.writeFileSync("./data.js",JSON.stringify(data));
        }
        res.write("<h1>注册页面</h1>");
    }else if(pathname==="/showUsers"){
        // 显示用户名和密码
       let users = JSON.parse( fs.readFileSync("./data.js"));
        let str = "<ul>";
        users.forEach(user=>{
            str += `<li>用户名是${user.username},密码是:${user.pwd}</li>`
        })
        str += "</ul>";
        res.write(str);
    }else if(pathname==="/showRegister"){
        // 加载regiter.html页面
        let htmldata = fs.readFileSync("./views/register.html");
        res.write(htmldata);
    } else{
        res.write("<h1>其他页面</h1>");
    }
    // res.write("hello");
    res.end();
})

server.listen(8989);